package com.banyuan.dao;

import com.banyuan.domain.User;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UserUtils {

    private static File file = new File("/Users/edy/Desktop/user.txt");


    // 查找所有的User
    public static List<User> listUser() throws IOException {
        List<User> userList = new ArrayList<>();
        List<String> stringList = FileUtils.readLines(file, "UTF-8");
        for (String s : stringList) {
            User user = strToUser(s);
            userList.add(user);
        }
        return userList;
    }

    // 往文件中增加 一个User对象
    public static void addUser(User user) throws IOException {
        FileUtils.writeStringToFile(file,userToString(user)+"\n","UTF-8",true);
    }

    public static void deleteUser(String name) throws IOException {
        List<User> userList = listUser();
        FileUtils.writeStringToFile(file,"","UTF-8");
        // 清空文档
        for (User user : userList) {
            if (!(user.getName().equals(name))) {
                addUser(user);
            }
        }
    }

    // 通过名字去找到一个对象User
    public static User getUser(String name) throws IOException {
        List<User> userList = listUser();
        for (User user : userList) {
            if (user.getName().equals(name)) {
                return user;
            }
        }
        return null;
    }

    // 通过传进来一个User去修改User的数据

    public static void updateUser(User updateUser) throws IOException {
        List<User> userList = listUser();
        FileUtils.writeStringToFile(file,"","UTF-8");
        for (User user : userList) {
            if (user.getName().equals(updateUser.getName())) {
                addUser(updateUser);
            } else {
                addUser(user);
            }
        }
    }

    // 通过传入一个String 名字，来查找所有包含这个String的User对象
    public static List<User> findUser(String str) throws IOException {
        List<User> userList = listUser();
        List<User> findList = new ArrayList<>();
        for (User user : userList) {
            if (user.getName().contains(str)) {
                findList.add(user);
            }
        }
        return findList;
    }


    // str转User

    public static User strToUser(String str) {
        String[] split = str.split(",");
        User user = new User(split[0],split[1],split[2],split[3]);
        return user;
    }

    //User对象转String
    public static String userToString(User user) {
        return user.getName()+","+user.getAge()+","+user.getSex()+","+user.getAddress();
    }
}












